from settings import DATABASE_FILE, SESSIONS_FOLDER, SEP
import sqlite3
from telethon import TelegramClient
from database import create_new_main_db, add_account


def add_new_account():
    phone = input("Phone: ")
    password = input("Password (Telegram): ")
    safelogin = input("SafeUMlogin (Not necessary): ")
    password_2 = input("Password(SafeUM) (Not necessary): ")
    api_id = input("Api_id: ")
    api_hash = input("Api_hash: ")
    is_working = int(input("Is active(0, 1): "))
    wallet = input("Wallet: ")
    wallet_pass = input("Wallet password (Coinomi) (Not necessary): ")
    recover_phrase = input("Wallet recover phrase (Not necessary): ")

    try:
        db = sqlite3.connect(DATABASE_FILE)
        db.close()
    except Exception as e:
        create_new_main_db()

    add_account(phone, password, api_id, api_hash, is_working, wallet, wallet_pass,
                recover_phrase, safelogin, password_2)


def add_new_information():
    phone = input("Phone: ")
    telegram_pass = input("Telegram password: ")
    api_id = input("Api_id: ")
    api_hash = input("Api_hash: ")
    is_working = int(input("is_working(0, 1)"))

    db = sqlite3.connect(DATABASE_FILE)
    cur = db.cursor()
    new_id = cur.execute("SELECT ID FROM Account WHERE PHONE = {}".format(phone)).fetchall()

    session = SESSIONS_FOLDER + SEP + "anon" + str(new_id[0]) + '.session'
    client = TelegramClient(session, int(api_id), api_hash)
    client.start()

    cur.execute("UPDATE Account "
                "SET API_ID = {}, API_HASH = {}, IS_ACTIVE = {}, SESSION = {}, PASS = {} "
                "WHERE  phone = {}".format(api_id, api_hash, is_working, session, telegram_pass, phone))

    db.commit()


def add_proxy():
    db = sqlite3.connect(DATABASE_FILE)
    cur = db.cursor()
    proxy_ip = input("ip: ")
    protocol = input("protocol: ")
    port = input("port: ")
    cur.execute("""INSERT INTO Proxy(IP, PROTOCOL, PORT) VALUES (?, ?, ?);""", (proxy_ip, protocol, port))
    db.commit()


while True:

    mode = input("New account (1) \nUpdate information (2)")

    if mode == '1':
        add_new_account()
    elif mode == '2':
        add_new_information()

    res = input("Continue? Y/n \n")
    if res == 'n':
        print("Exiting...")
        break
